# encoding: UTF-8
class ApplicationController < ActionController::Base
  #after_filter :store_location

  # User: Trước khi vào các trang đặc biệt, kiểm tra đã log in hay chưa
  before_filter :authenticate_user #, :only => [:account_settings, :set_account_info]
  # End - User

  protect_from_forgery
  include SessionsHelper

  # User
  helper_method :current_user
  # Test OK
  def current_user

    # Note: we want to use "find_by_id" because it's OK to return a nil.
    # If we were to use User.find, it would throw an exception if the user can't be found.
    @current_user ||= NhanVien.find_by_id(session[:user_id]) if session[:user_id]
    @current_user ||= NhanVien.find_by_authentication_token(cookies[:auth_token]) if cookies[:auth_token] && @current_user.nil?
    @current_user
  end

  def authenticate_user
    #if current_user.nil?
    #  flash[:error] = 'Bạn phải đăng nhập để xem được nội dung trang này!'
    #  redirect_to :root
    #end

    #puts current_user.to_yaml
    #puts current_user.ChucVu
    if self.class.to_s == "TaiSansController" || self.class.to_s == "LoaiTsController" || self.class.to_s == "PhongsController" || self.class.to_s == "ThongKesController" || self.class.to_s == "NhanViensController" || self.class.to_s == "PhieuNhapsController"
      if current_user.nil? || (!current_user.nil? && (current_user.MaCV_id == 2 || current_user.MaCV_id == 3))
        flash[:error] = 'Bạn không có quyền xem nội dung trang này!'
        redirect_to :root
      end
    end
  end
  # End - User
end
